package com.itheima.sky.interceptors.front;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.sky.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description SessionInterceptor
 * @Author jiangning
 * @Date 2024-06-28
 */
@Slf4j
@Component
public class SessionInterceptorFront implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            // 如果接下来不是前往控制器(可能访问静态资源)
            return true;
        }

        HttpSession session = req.getSession();
        String referer = req.getHeader("referer");

        if (referer != null && referer.contains("/backend/")) {
            // 校验 empId
            if (session.getAttribute("empId") != null) {
                return true;
            }
        } else {
            // 校验 userId
            if (session.getAttribute("userId") != null) {
                return true;
            }
        }

        res.setStatus(200);
        res.getWriter().print(new ObjectMapper().writeValueAsString(Result.error("NOTLOGIN")));
        return false;
    }
}
